//
//  WmcHomeVM+JoinTeam.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/28.
//

import Foundation

extension WmcHomeVM {
    
    /// 搜索团队号加入
    /// - Parameter teamId: 团队ID
    /// - Returns: description
    func joinTeam(teamId: Int?,succeed:((_ teamAlbum: WmcMediaTeamAlbumModel) -> Void)?) -> Void {
        WmcMediaTeamManagerAPI.addMember(teamId: teamId,type: .wechat).subscribe { res in
            guard let succeed = succeed else {
                return
            }
            WmcNotificationManager.shared.post(type: .joinTeamSucceed, object: nil)
            /// 同步配置
            let config = WmcMediaAlbumConfigurationModel.init()
            config.albumType = 1
            config.isSync = true
            config.name = res.remark ?? ""
            config.albumId = res.teamId ?? 0
            config.busId = res.teamId ?? 0
            WmcPreferenceSettingsManager.addTeamSyncConfig(model: config)
            
            self.getCurrentJoinedTeamAlbum(teamId: teamId ?? 0) { teamAlbum in
                succeed(teamAlbum)
            }
        } onError: { error in
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
    
    /// 查询当前加入的团队
    /// - Parameter page: 页码
    /// - Returns: description
    func getCurrentJoinedTeamAlbum(teamId: Int,succeed: ((_ teamAlbum: WmcMediaTeamAlbumModel) -> Void)?) -> Void {
        //通过page的值判断是下拉还是上拉(可以用枚举)
        WmcHudManager.loading()
        WmcMediaTeamAlbumAPI.fetchTeamAlbumList().subscribe { list in
            guard let succeed = succeed else {
                return
            }
            WmcHudManager.dismiss()
            list.forEach { album in
                if album.teamId == teamId {
                    succeed(album)
                }
            }
        } onError: { error in
            WmcHudManager.toast(error)
            WmcHudManager.dismiss()
        }.disposed(by: rx.disposeBag)
    }
}
